﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

/*
 * UDP info
 * 
 * Packets in UDP
 * http://www.coders4fun.com/en/2007/10/04/udp-sender-message/
 * How to calculate checksum of UDP packet
 * http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=60632
 * Object convert to bytes
 * http://www.matthew-long.com/2005/10/18/memory-pinning/
 * Mapping a byte array to a structure in C#
 * http://geekswithblogs.net/taylorrich/archive/2006/08/21/88665.aspx
 * // server udp
 * http://www.java2s.com/Code/CSharp/Network/UdpServerSample.htm
 */

namespace J2i.Net.XnaXboxController
{
    class udpSocket
    {

       
       UdpClient client;
       IPEndPoint ipep;

       public udpSocket(string ip, int port) 
       {
           client = new UdpClient(ip, port);
           ipep = new IPEndPoint(IPAddress.Any, 9050);
       }
       
       public int receive()
       {
           byte[] dataIn = new byte[4 * 2];
           IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
           dataIn = client.Receive(ref sender);
           int id = BitConverter.ToInt32(dataIn, 0);
           int team = BitConverter.ToInt32(dataIn, 4);
           return 0;
       }

       public void sendMessage(int button, int team, int id, int value)
       {
    
           byte [] array1 = new byte[4];
           byte [] array2 = new byte[4];
           byte [] array3 = new byte[4];
           byte [] array4 = new byte[4];

           array1 = BitConverter.GetBytes(button);
           array2 = BitConverter.GetBytes(team);
           array3 = BitConverter.GetBytes(id);
           array4 = BitConverter.GetBytes(value);

           byte[] dataOut2 = new byte[4*4];
           
           System.Buffer.BlockCopy(array1, 0, dataOut2, 0,  4);
           System.Buffer.BlockCopy(array2, 0, dataOut2, 4,  4);
           System.Buffer.BlockCopy(array3, 0, dataOut2, 8,  4);
           System.Buffer.BlockCopy(array4, 0, dataOut2, 12, 4);

           // Send data
           client.Send(dataOut2, dataOut2.Length);
       }  

       public void close()
       {
           client.Close();
       }

        
    }
}
